package com.hfxt.j96springboot.web;


import com.alibaba.fastjson.JSONArray;
import com.hfxt.j96springboot.entity.TbUser;
import com.hfxt.j96springboot.service.TbUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller  //@Controller+@Responsebody
@RequestMapping("/user")
public class UserController {

    @Resource
    private TbUserService tbUserService;

    @RequestMapping("/hello.html")
    @ResponseBody
    public String hello(){
        return "hello,springboot";
    }

    @RequestMapping("/index.html")
    public String index(){
        System.out.println("xxxx");
        return "index";
    }

    @RequestMapping("login.html")
    @ResponseBody
    public  String login(TbUser tbUser){
        Map<String,Object> maps=new HashMap<>();
        TbUser tbUser1=tbUserService.getUserByUsername(tbUser.getUsername());
        if(tbUser1==null){
            maps.put("code","-1");
            maps.put("msg","账户不存在");
        }else if(!tbUser1.getPassword().equals(tbUser.getPassword())){
            maps.put("code","-1");
            maps.put("msg","密码不正确");
        }else{
            maps.put("code","1");
            maps.put("msg","登录成功");
        }
        return JSONArray.toJSONString(maps);
    }



    @RequestMapping("shirologin.html")
    @ResponseBody
    public  String shirologin(TbUser tbUser){
        Map<String,Object> maps=new HashMap<String,Object>();

        try{
            //创建shiro的认证对象
            Subject subject= SecurityUtils.getSubject();
            UsernamePasswordToken token=new UsernamePasswordToken(tbUser.getUsername(),tbUser.getPassword());
            //提交认证
            subject.login(token);  //跑到用户自定义的realm实现认证加授权的操作
            //获得成功认证的对象
            TbUser loginuser=(TbUser)SecurityUtils.getSubject().getPrincipal();
            maps.put("code",1);
            maps.put("msg","认证成功");
            maps.put("loginuser",loginuser);
        }catch (UnknownAccountException e){
            maps.put("code",0);
            maps.put("msg","用户名不正确");
        }catch (IncorrectCredentialsException e){
            maps.put("code",0);
            maps.put("msg","密码不正确");
        } catch (AuthenticationException e){
            maps.put("code",0);
            maps.put("msg","认证失败，请联系管理员");
        }
        return JSONArray.toJSONString(maps);
    }
}
